package com.gm.commonlib.util.stringUtils;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {


    public static int indexOf(String str, char searchChar, int startPos) {
        return isEmpty(str) ? -1 : str.indexOf(searchChar, startPos);
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0 || TextUtils.isEmpty(str);
    }

    public static boolean isNumberEmpty(String str) {
        return TextUtils.isEmpty(str) || "0".equals(str);
    }

    public static boolean numberIsZero(String str) {
        if (!TextUtils.isEmpty(str) && Double.parseDouble(str) == 0) {
            return true;
        }
        return false;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str != null && (strLen = str.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    public static String trim(String str) {
        return str == null ? null : str.trim();
    }

    public static String reverse(String str) {
        return str == null ? null : (new StringBuffer(str)).reverse().toString();
    }

    public static boolean equals(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equals(str2);
    }

    public static boolean equalsIgnoreCase(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
    }

    public static String getLimitedLenghtString(String str, int length) {
        int len = str.length();
        return isEmpty(str) ? "" : (len < length ? str.substring(0, len) : str.substring(0, length) + "...");
    }

    public static String String2Json(String s) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); ++i) {
            char c;
            switch (c = s.toCharArray()[i]) {
                case '\b':
                    sb.append("\\b");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\"':
                    sb.append("\\\"");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                default:
                    sb.append(c);
            }
        }

        return sb.toString();
    }

    public static boolean isLetterDigitOrChinese(String str) {
        return str.matches("^[A-Za-z0-9\\u4e00-\\u9fa5]+$");
    }

    public static boolean isLetterDigitOrChineseFUH(String str) {
        String REGEX_GROUP_INFO = "^[A-Za-z0-9 \\n\\r，。,.！!、~～?？“”()（）\\\\[\\\\]【】\\u4e00-\\u9fa5-—]+$";
        return str.matches(REGEX_GROUP_INFO);
    }

    public static String buildString(String mask, int len) {
        StringBuilder builder = new StringBuilder();
        buildString(mask, len, builder);
        return builder.toString();
    }

    public static StringBuilder buildString(String mask, int len, StringBuilder builder) {
        if (mask != null && builder != null) {
            for (int i = 0; i < len; i++) {
                builder.append(mask);
            }
        }
        return builder;
    }

    public static String makeNotNullString(String value) {
        return makeNotNullString(value, "");
    }

    public static String makeNotNullString(String value, String defaultValue) {
        if (value == null) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * 验证字符是否无效
     * 等效于isEmpty||isBlank
     *
     * @param str
     * @return
     */
    public static boolean isStringInvalid(String str) {
        return isEmpty(str) || isBlank(str);
    }

    /**
     * 验证字符有效性
     * 等同于 ！isStringInvalid
     *
     * @param str
     * @return
     */
    public static boolean isStringValid(String str) {
        return !isStringInvalid(str);
    }

    public static String getNoneWhiteSpaceString(String value) {
        if (TextUtils.isEmpty(value)) {
            return null;
        }
        return value;
    }

    public static String replace(String value, String regularExpression, String replacement) {
        if (value == null) {
            return "";
        }
        return value.replaceAll(regularExpression, replacement);
    }


    public static String makeStringFromList(List<String> stringList, String speartor) {
        if (stringList == null) {
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder();
        int count = stringList.size();
        for (int i = 0; i < count; i++) {
            stringBuilder.append(stringList.get(i));
            if (i != count - 1) {
                stringBuilder.append(speartor);
            }
        }

        return stringBuilder.toString();
    }

    public static String formatPersonIdentity(String personIdentity) {
        StringBuilder builder = new StringBuilder();

        if (personIdentity != null) {
            if (personIdentity.length() >= 18) {
                builder.append(personIdentity.substring(0, 3));
                buildString("*", 18 - 7, builder);
                builder.append(personIdentity.substring(personIdentity.length() - 4));
            } else if (personIdentity.length() >= 15) {
                builder.append(personIdentity.substring(0, 3));
                buildString("*", 15 - 7, builder);
                builder.append(personIdentity.substring(personIdentity.length() - 4));
            } else {
                if (personIdentity.length() > 7) {
                    builder.append(personIdentity.substring(0, 3));
                    buildString("*", personIdentity.length() - 7, builder);
                    builder.append(personIdentity.substring(personIdentity.length() - 4));
                } else {
                    builder.append(personIdentity);
                }
            }
        }

        return builder.toString();
    }

    public static String mastMobile(String personIdentity) {
        StringBuilder builder = new StringBuilder();

        if (personIdentity != null) {
            if (personIdentity.length() >= 11) {
                builder.append(personIdentity.substring(0, 3));
                buildString("*", 11 - 7, builder);
                builder.append(personIdentity.substring(personIdentity.length() - 4));
            } else if (personIdentity.length() > 7) {
                builder.append(personIdentity.substring(0, 3));
                buildString("*", 11 - 7, builder);
                builder.append(personIdentity.substring(personIdentity.length() - 4));
            } else {
                builder.append(personIdentity);
            }
        }

        return builder.toString();
    }

    public static String formatBankNumber(String personIdentity) {
        StringBuilder builder = new StringBuilder();

        if (personIdentity != null) {
            buildString("*", 4, builder).append(" ");
            buildString("*", 4, builder).append(" ");
            buildString("*", 4, builder).append(" ");
            if (personIdentity.length() > 4) {
                builder.append(personIdentity.substring(personIdentity.length() - 4));
            } else {
                builder.append(personIdentity);
            }
        }

        return builder.toString();
    }

    /**
     * Convert string to DBC.
     *
     * @param s The string.
     * @return the DBC string
     */
    public static String toDBC(final String s) {
        if (s == null || s.length() == 0) return "";
        char[] chars = s.toCharArray();
        for (int i = 0, len = chars.length; i < len; i++) {
            if (chars[i] == 12288) {
                chars[i] = ' ';
            } else if (65281 <= chars[i] && chars[i] <= 65374) {
                chars[i] = (char) (chars[i] - 65248);
            } else {
                chars[i] = chars[i];
            }
        }
        return new String(chars);
    }

    public static String getNumber(String data) {
        if (data == null) {
            return data;
        }
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(data);
        return m.replaceAll("").trim();
    }


    public static String getEnglishWord(String data) {
        if (data == null) {
            return data;
        }
        Pattern pattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = pattern.matcher(data);
        String match="";
        while (matcher.find()) {
            match= matcher.group();
        }
        if (match!=null){
            match.trim();
        }
        return match;
    }

    //TODO 获取字符串 最后几个字符组成的字符串
    public static String getEndStringByLen(String value, int len) {
        if (len <= 0 || isEmpty(value)) {
            return "";
        }
        if (value.length() > len) {
            return value.substring(value.length() - len);
        }
        return value;
    }

    /**
     * 车牌号加-
     *
     * @param licensePlateNo
     * @return
     */
    public static String getLicensePlateNo(String licensePlateNo) {
        if (TextUtils.isEmpty(licensePlateNo)) {
            return licensePlateNo;
        } else {
            if (licensePlateNo.contains("-")) {
                return licensePlateNo;
            }
            if (licensePlateNo.length() <= 2) {
                return licensePlateNo;
            }
            char firstData = licensePlateNo.charAt(0);
            if (isChinese(firstData)) {
                return licensePlateNo.substring(0, 2) + "-" + licensePlateNo.substring(2, licensePlateNo.length());
            }
            return licensePlateNo;
        }
    }

    //字母是否为中文
    public static boolean isChinese(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5]");

    }

    public static String getDunNumFromString(String dun) {
        if (TextUtils.isEmpty(dun)) {
            return dun;
        }
        return dun.replace("吨", "");
    }


    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isQuote(char codePoint) {
        return (codePoint == '\'') || (codePoint == '\"');
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsQuote(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isQuote(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    public static StringArrayBuilder getStringArrayBuilder() {
        return new StringArrayBuilder();
    }

    public static StringArrayBuilder getStringArrayBuilder(boolean allowEmpty) {
        return new StringArrayBuilder(allowEmpty);
    }


    public static class StringArrayBuilder {

        boolean allowEmpty;
        List<String> stringList = null;

        StringArrayBuilder(boolean allowEmpty) {
            this.allowEmpty = allowEmpty;
            stringList = new ArrayList<>();
        }

        StringArrayBuilder() {
            allowEmpty = false;
            stringList = new ArrayList<>();
        }

        public StringArrayBuilder addString(String value) {
            if (!TextUtils.isEmpty(value)) {
                stringList.add(value);
            } else if (allowEmpty) {
                stringList.add(value);
            }
            return this;
        }

        public String build(String commas) {
            if (commas == null) {
                commas = ",";
            }
            return makeStringFromList(stringList, commas);
        }

        public int getValueCount() {
            return stringList.size();
        }

        public void reset() {
            stringList.clear();
        }
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-", "");
    }

    //拼接字符串
    public static String join(String regex, List<String> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < params.size(); i++) {
            String s = params.get(i);
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                if (i != params.size() - 1 && !TextUtils.isEmpty(regex)) {
                    sb.append(regex);
                }
            }
        }
        String ret = "";
        if (sb.length() > 0) {
            ret = sb.toString();
        }
        return ret;
    }

    //拼接字符串
    public static String join(String regex, String... params) {
        StringBuffer sb = new StringBuffer();
        for (String s : params) {
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                if (!TextUtils.isEmpty(regex)) {
                    sb.append(regex);
                }
            }
        }
        String ret = "";
        if (sb.length() > 0) {
            ret = sb.deleteCharAt(sb.length() - (!TextUtils.isEmpty(regex) ? regex.length() : 0)).toString();
        }
        return ret;
    }

    public static String cnToEncode(String s ){
        char[] ch = s.toCharArray();
        String result = "";
        for(int i=0;i<ch.length;i++){
            char temp = ch[i];
            if(isChinese(temp)){
                try {
                    String encode = URLEncoder.encode(String.valueOf(temp), "utf-8");
                    result = result + encode;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                result = result+temp;
            }
        }
        return result;
    }



}
